package com.resou.reader;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppWakeUpAdapter;
import com.fm.openinstall.model.AppData;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.ShareTimeBean;
import com.resou.reader.bookshelf.HomeBookShelfFragment;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.bookstore.HomeBookStoreFragment;
import com.resou.reader.commom.Constant;
import com.resou.reader.discovery.HomeDiscoveryFragment;
import com.resou.reader.mine.HomeUserCenterFragment;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.login.LoginActivity;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.reader.utils.SpUtils;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.StatusBarUtil;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.WXUtils;
import com.resou.reader.utils.eventbus.LoadBookEvent;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.view.Loading;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class MainActivity extends AppCompatActivity implements IMainContract.IMainView {

    MainPresenter mPresenter;

    public static final String HOME_BOOK_SHELF_FRAGMENT = "HomeBookShelfFragment";
    public static final String HOME_BOOK_STORE_FRAGMENT = "HomeBookStoreFragment";
    public static final String HOME_DISCOVERY_FRAGMENT = "HomeDiscoveryFragment";
    public static final String HOME_USER_CENTER_FRAGMENT = "HomeUserCenterFragment";
    public static final String MESSAGE_RECEIVED_ACTION = "com.resou.reader.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public int currentIndex = 0;
    @BindView(R.id.home_book_shelf_layout)
    LinearLayout mHomeBookShelfLayout;
    @BindView(R.id.home_book_store_layout)
    LinearLayout mHomeBookStoreLayout;
    @BindView(R.id.home_discovery_layout)
    LinearLayout mHomeDiscoveryLayout;
    @BindView(R.id.home_user_center_layout)
    LinearLayout mHomeUserCenterLayout;

    /**
     * 记录上次选中的Layout
     */
    LinearLayout mSelectedLayout;
    Unbinder unbinder;
    private HomeBookShelfFragment mHomeBookShelfFragment;
    private HomeBookStoreFragment mHomeBookStoreFragment;
    private HomeDiscoveryFragment mHomeDiscoveryFragment;
    private HomeUserCenterFragment mHomeUserCenterFragment;
    private static final String TAG = "MainActivity-App";
    public static MainActivity instance;
    public static boolean isForeground = false;

    public static MainActivity getInstance() {
        return instance;
    }

    public static void start(Context context) {
        Intent starter = new Intent(context, MainActivity.class);
//    starter.putExtra();
        context.startActivity(starter);
    }

    public int getState() {
        if (ScreenUtils.hasNotchScreen(this)) {
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId != 0) {
                return (int) ScreenUtils.convertDpToPixel(getResources().getDimensionPixelSize(resourceId), this) + 10;
            }
        }

        return 0;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;

        //TODO  添加状态栏代码  szc
        //透明状态栏/导航栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
        }
        //使得布局延伸到状态栏和导航栏区域
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);


        setContentView(R.layout.activity_main);
        //获取唤醒参数
        OpenInstall.getWakeUp(getIntent(), wakeUpAdapter);
        PushAgent.getInstance(this).onAppStart();
        unbinder = ButterKnife.bind(this);
        MobclickAgent.onPageStart("MainActivity");
        if (savedInstanceState != null) {
            mHomeBookShelfFragment = (HomeBookShelfFragment) getSupportFragmentManager().findFragmentByTag(HOME_BOOK_SHELF_FRAGMENT);
            mHomeBookStoreFragment = (HomeBookStoreFragment) getSupportFragmentManager().findFragmentByTag(HOME_BOOK_STORE_FRAGMENT);
            mHomeDiscoveryFragment = (HomeDiscoveryFragment) getSupportFragmentManager().findFragmentByTag(HOME_DISCOVERY_FRAGMENT);
            mHomeUserCenterFragment = (HomeUserCenterFragment) getSupportFragmentManager().findFragmentByTag(HOME_USER_CENTER_FRAGMENT);
        }
        mPresenter = new MainPresenter(this);

        int defaultPosition = 0;
        //获取网络服务
        boolean isConnected = NetworkUtils.isNetworkConnected(this);
        if (isConnected) {
            initData();
        }
        setTabSelection(defaultPosition);

        //动态获取权限，解决安卓6.0以上权限适配问题
        setPermission();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    /*
        动态申请权限
     */
    private void setPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        //所有权限都被申请
                    } else {
                        //至少有一个权限被拒绝
                    }
                });
    }


    private static final int BAIDU_READ_PHONE_STATE = 100;//定位权限请求
    private static final int TAGFINDRESULT = 2;//发现页面的的onActivityResult回调
    private static final int PRIVATE_CODE = 1315;//开启GPS权限
    private static final String[] LOCATIONGPS = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (TAGFINDRESULT == resultCode) {
            mHomeDiscoveryFragment.onActivityResult(resultCode, resultCode, data);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        // 处理Umeng推送启动的页面
        checkWeatherFromUmeng();
        System.gc();
    }

    /**
     * 是否来自Umeng的推送
     */
    private void checkWeatherFromUmeng() {
        String strPosition = getIntent().getStringExtra("select_position");
        if (!TextUtils.isEmpty(strPosition)) {
            try {
                int selectPosition = Integer.parseInt(strPosition);
                setTabSelection(selectPosition);
                getIntent().putExtra("select_position", 0);//默认又回到书架
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        MobclickAgent.onPageEnd("MainActivity");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            UMShareAPI.get(this).release();
        } catch (OutOfMemoryError error) {
            Log.e(TAG, "onDestroy: " + error.getMessage());
        }
    }


    @OnClick({R.id.home_book_shelf_layout, R.id.home_book_store_layout, R.id.home_discovery_layout, R.id.home_user_center_layout})
    public void onClick(View view) {
        int index = 0;
        switch (view.getId()) {
            case R.id.home_book_shelf_layout:
//                throw new NullPointerException("测试异常！检测是否统计到!");
                break;
            case R.id.home_book_store_layout:
                index = 1;
                break;
            case R.id.home_discovery_layout:
                index = 2;
                break;
            case R.id.home_user_center_layout:
                index = 3;
                break;
        }
        currentIndex = index;
        setTabSelection(index);
        resetLayout(index);
    }

    public void setTabSelection(int index) {
        if (index > 3) {
            index = 0;
        }
        if (index == 1 || index == 2 || index == 3) {
//            if (PreferenceUtil.getInstance(this).isShowFifteenDaysDialog()) {
//                DialogManager.showFifteenFreeDialog(getSupportFragmentManager());
//            }
        }
        resetLayout(index);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (mHomeBookShelfFragment == null) {
                    mHomeBookShelfFragment = new HomeBookShelfFragment();
                    transaction.add(R.id.fragment_parent, mHomeBookShelfFragment, HOME_BOOK_SHELF_FRAGMENT);
                } else {
                    transaction.show(mHomeBookShelfFragment);
                }
                break;
            case 1:
                if (mHomeBookStoreFragment == null) {
                    mHomeBookStoreFragment = new HomeBookStoreFragment();
                    transaction.add(R.id.fragment_parent, mHomeBookStoreFragment, HOME_BOOK_STORE_FRAGMENT);
//                    StatusBarUtil.setStatusBarColor(this, getResources().getColor(android.R.color.transparent));
                } else {
//                    StatusBarUtil.setStatusBarColor(this, getResources().getColor(android.R.color.transparent));
                    transaction.show(mHomeBookStoreFragment);
                }
                break;
            case 2:
                if (mHomeDiscoveryFragment == null) {
                    mHomeDiscoveryFragment = new HomeDiscoveryFragment();
                    transaction.add(R.id.fragment_parent, mHomeDiscoveryFragment, HOME_DISCOVERY_FRAGMENT);
                } else {
                    transaction.show(mHomeDiscoveryFragment);
                }
                break;
            case 3:
                if (mHomeUserCenterFragment == null) {
                    mHomeUserCenterFragment = new HomeUserCenterFragment();
                    transaction.add(R.id.fragment_parent, mHomeUserCenterFragment, HOME_USER_CENTER_FRAGMENT);
                } else {
                    transaction.show(mHomeUserCenterFragment);
                }

                break;
            default:
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (mHomeBookShelfFragment != null)
            transaction.hide(mHomeBookShelfFragment);
        if (mHomeBookStoreFragment != null)
            transaction.hide(mHomeBookStoreFragment);
        if (mHomeDiscoveryFragment != null)
            transaction.hide(mHomeDiscoveryFragment);
        if (mHomeUserCenterFragment != null)
            transaction.hide(mHomeUserCenterFragment);
    }

    private void resetLayout(int index) {
        if (index > 3) {
            index = 0;
        }
        if (mSelectedLayout != null) {
            mSelectedLayout.setSelected(false);
        }
        switch (index) {
            case 0:
                mHomeBookShelfLayout.setSelected(true);
                mSelectedLayout = mHomeBookShelfLayout;
                break;
            case 1:
                mHomeBookStoreLayout.setSelected(true);
                mSelectedLayout = mHomeBookStoreLayout;
                break;
            case 2:
                mHomeDiscoveryLayout.setSelected(true);
                mSelectedLayout = mHomeDiscoveryLayout;
                break;
            case 3:
                mHomeUserCenterLayout.setSelected(true);
                mSelectedLayout = mHomeUserCenterLayout;
                break;
            default:
                break;
        }
    }

    //记录用户首次点击返回键的时间
    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (Loading.getInstance().isShow()) {
                Loading.getInstance().dismiss();
            }
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime < 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void autoLoginSuccess(LoginData data) {
        if (mHomeUserCenterFragment != null) {
            mHomeUserCenterFragment.initUserInfo(data);
        }
        sendBroadcast(new Intent(Constant.BC_BATCH_PAY));
        sendBroadcast(new Intent(Constant.BC_READER));
    }

    @Override
    public void autoLoginFailed(int reason) {
        if (reason == 401) {
            //退出登录
            UserInstance.setLoginData(null);
            UserInstance.setToken("");
            SpUtils.clearLoginState(this);

            //通知其他界面更新
            MessageEvent event = new MessageEvent();
            event.isLogin = false;
            EventBus.getDefault().post(event);
            try {
                ToastUtil.makeLongToast("登录已过期，请重新登录！");
                mPresenter.touristLogin(DeviceUtils.getAndroidId(this));
                LoginActivity.start(this);
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 此处要调用，否则App在后台运行时，会无法截获
        OpenInstall.getWakeUp(intent, wakeUpAdapter);

        setTabSelection(intent.getIntExtra("index", 0));
        resetLayout(intent.getIntExtra("index", 0));
    }

    @Override
    public void touristSuccess() {
        mPresenter.saveRechargeActivityState(this);
        EventBus.getDefault().post(new LoadBookEvent());
        EventBus.getDefault().post(new BookCollection());
        //登录成功后让其他地方更新登录信息
        MessageEvent event = new MessageEvent();
        event.isLogin = true;
        EventBus.getDefault().post(event);
    }

    @Override
    public void showUpdate(String url) {

    }

    @Override
    public void setToastShow() {

    }

    @Override
    public void InstallApk(String path) {

    }

    @Override
    public Activity getContext() {
        return null;
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void showError(Throwable throwable) {
        ToastUtil.makeShortToast(throwable.getMessage() + "");
    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void initData() {
        mPresenter.autoLogin();
        mPresenter.quearAdProbability();
        /**
         * 判断是否是登录，未登录 就调用游客接口
         */
        if (!UserInstance.isLogin()) {
            mPresenter.touristLogin(DeviceUtils.getAndroidId(this));
        }
    }

    AppWakeUpAdapter wakeUpAdapter = new AppWakeUpAdapter() {
        @Override
        public void onWakeUp(AppData appData) {
            //获取渠道数据
            String channelCode = appData.getChannel();
            //获取绑定数据
            String bindData = appData.getData();
            Log.d("OpenInstall", "getWakeUp : wakeupData = " + appData.toString());
        }
    };


    /**
     * 分享
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ShareTimeBean event) {
        UMWeb web = new UMWeb("http://rs.resouxs.com/down.html?channelCode=APP");
        web.setTitle("平台补贴，海量正版书籍免费看！");
        web.setDescription("我正在用热搜小说APP看书，推荐给你，一起来看书吧~");
        new ShareAction(this)
                .withMedia(web)
                .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QZONE)
                .setCallback(umShareListener).open();
    }

    private UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            switch (platform) {
                case WEIXIN:
                case WEIXIN_CIRCLE:
                    if (!WXUtils.isWeixinAvilible(MainActivity.this)) {
                        ToastUtil.makeShortToast("您未安装微信，请选择其他分享方式");
                        return;
                    }
                    break;
                case QZONE:
                case QQ:
                    if (!WXUtils.isQQClientAvailable(MainActivity.this)) {
                        ToastUtil.makeShortToast("您未安装QQ，请选择其他分享方式");
                        return;
                    }
                    break;
            }
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
        }
    };
}
